<template>
  <div class="order-container">
    <div class="filter-container">
      <el-input
        v-model="queryParams.keyword"
        placeholder="请输入查询内容"
        clearable
        style="width: 220px; margin-right: 10px"
      >
        <template #prefix>
          <el-icon class="el-input__icon"><Search /></el-icon>
        </template>
      </el-input>

      <el-date-picker
        v-model="queryParams.dateRange"
        type="daterange"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        style="width: 340px; margin-right: 10px"
      />

      <el-select
        v-model="queryParams.payStatus"
        placeholder="支付状态"
        clearable
        style="width: 160px; margin-right: 10px"
      >
        <el-option label="未支付" value="unpaid" />
        <el-option label="已支付" value="paid" />
      </el-select>

      <el-select
        v-model="queryParams.status"
        placeholder="订单状态"
        clearable
        style="width: 160px; margin-right: 10px"
      >
        <el-option label="正常" value="normal" />
        <el-option label="已取消" value="cancelled" />
        <el-option label="已使用" value="used" />
      </el-select>

      <el-button type="primary" @click="handleQuery">
        <el-icon><Search /></el-icon>搜索
      </el-button>
      <el-button @click="resetQuery">
        <el-icon><Refresh /></el-icon>重置
      </el-button>
    </div>

    <el-table v-loading="loading" :data="orderList" border style="width: 100%">
      <el-table-column prop="id" label="订单ID" />
      <el-table-column prop="userName" label="用户姓名" />
      <el-table-column prop="courtName" label="场地名称" />
      <el-table-column label="预约时间" width="320">
        <template #default="scope">
          {{ formatDateTime(scope.row.startTime) }} 至
          {{ formatDateTime(scope.row.endTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="totalAmount" label="总金额">
        <template #default="scope"> {{ scope.row.totalAmount }}元 </template>
      </el-table-column>
      <el-table-column prop="payStatus" label="支付状态" width="100">
        <template #default="scope">
          <el-tag
            :type="scope.row.payStatus === 'paid' ? 'success' : 'warning'"
          >
            {{ scope.row.payStatus === "paid" ? "已支付" : "未支付" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="订单状态">
        <template #default="scope">
          <el-tag :type="getOrderStatusType(scope.row.status)">
            {{ getOrderStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            :icon="View"
            @click="handleDetail(scope.row)"
          >
            详情
          </el-button>
          <!-- <el-button
            v-if="
              scope.row.payStatus === 'unpaid' && scope.row.status === 'normal'
            "
            size="small"
            type="success"
            :icon="Check"
            @click="handlePay(scope.row)"
          >
            支付
          </el-button>
          <el-button
            v-if="scope.row.status === 'normal'"
            size="small"
            type="danger"
            :icon="Delete"
            @click="handleCancel(scope.row)"
          >
            取消
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:currentPage="queryParams.pageNum"
      v-model:page-size="queryParams.pageSize"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      class="pagination"
    />

    <!-- 订单详情对话框 -->
    <el-dialog
      title="订单详情"
      v-model="detailDialog.visible"
      width="600px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="订单ID">{{
          detailForm.id
        }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{
          detailForm.userId
        }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{
          detailForm.userName
        }}</el-descriptions-item>
        <el-descriptions-item label="场地ID">{{
          detailForm.courtId
        }}</el-descriptions-item>
        <el-descriptions-item label="场地名称">{{
          detailForm.courtName
        }}</el-descriptions-item>
        <el-descriptions-item label="预约开始时间">{{
          formatDateTime(detailForm.startTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="预约结束时间">{{
          formatDateTime(detailForm.endTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="总金额"
          >{{ detailForm.totalAmount }}元</el-descriptions-item
        >
        <el-descriptions-item label="支付状态">
          <el-tag
            :type="detailForm.payStatus === 'paid' ? 'success' : 'warning'"
          >
            {{ detailForm.payStatus === "paid" ? "已支付" : "未支付" }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getOrderStatusType(detailForm.status)">
            {{ getOrderStatusText(detailForm.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          formatDateTime(detailForm.createTime)
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          formatDateTime(detailForm.updateTime)
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, View, Check, Delete, Refresh } from "@element-plus/icons-vue";
import * as orderApi from "@/api/order";

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  keyword: "",
  dateRange: [],
  payStatus: "",
  status: "",
});

// 表格数据
const orderList = ref([]);
const total = ref(0);
const loading = ref(false);

// 详情对话框
const detailDialog = reactive({
  visible: false,
});

// 详情表单数据
const detailForm = reactive({
  id: "",
  userId: "",
  userName: "",
  courtId: "",
  courtName: "",
  startTime: "",
  endTime: "",
  totalAmount: 0,
  payStatus: "",
  status: "",
  createTime: "",
  updateTime: "",
});

// 转换为后端需要的查询参数
const apiQueryParams = computed(() => {
  const params = {
    pageNum: queryParams.pageNum,
    pageSize: queryParams.pageSize,
    keyword: queryParams.keyword || undefined,
    payStatus: queryParams.payStatus || undefined,
    status: queryParams.status || undefined,
  };

  // 添加日期范围参数
  if (queryParams.dateRange && queryParams.dateRange.length === 2) {
    params.startTime = queryParams.dateRange[0] + " 00:00:00";
    params.endTime = queryParams.dateRange[1] + " 23:59:59";
  }

  return params;
});

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString();
};

// 生命周期钩子
onMounted(() => {
  getList();
});

// 获取订单列表
const getList = async () => {
  loading.value = true;
  try {
    const response = await orderApi.getOrderList(apiQueryParams.value);

    if (response.code === 200) {
      const data = response.data;
      orderList.value = data.list || [];
      total.value = data.total || 0;

      // 补充场地名称和用户名称（实际项目中可能需要额外调用API获取）
      orderList.value.forEach((order) => {
        // 这里可能需要根据实际情况补充场地和用户信息
        if (!order.courtName) {
          order.courtName = `场地${order.courtId}`;
        }
        if (!order.userName) {
          order.userName = `用户${order.userId}`;
        }
      });
    } else {
      ElMessage.error(response.message || "获取订单列表失败");
    }
  } catch (error) {
    console.error("获取订单列表出错", error);
    ElMessage.error("获取订单列表出错，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1;
  queryParams.payStatus = "";
  queryParams.status = "";
  queryParams.keyword = "";
  queryParams.dateRange = [];
  getList();
};

// 分页操作
const handleSizeChange = (size) => {
  queryParams.pageSize = size;
  getList();
};

const handleCurrentChange = (num) => {
  queryParams.pageNum = num;
  getList();
};

// 详情按钮操作
const handleDetail = async (row) => {
  try {
    // 先获取最新订单详情
    const response = await orderApi.getOrderById(row.id);
    if (response.code === 200) {
      const orderDetail = response.data;
      // 合并详情数据
      Object.assign(detailForm, row, orderDetail);
      detailDialog.visible = true;
    } else {
      ElMessage.error(response.message || "获取订单详情失败");
    }
  } catch (error) {
    console.error("查看订单详情出错", error);
    ElMessage.error("查看订单详情出错，请稍后重试");
  }
};

// 支付按钮操作
const handlePay = (row) => {
  ElMessageBox.confirm(`确认将订单 ${row.id} 标记为已支付吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await orderApi.updatePayStatus(row.id, "paid");
        if (response.code === 200) {
          ElMessage.success("支付状态更新成功");
          // 更新本地数据
          row.payStatus = "paid";
          // 刷新列表
          getList();
        } else {
          ElMessage.error(response.message || "支付状态更新失败");
        }
      } catch (error) {
        console.error("支付状态更新出错", error);
        ElMessage.error("支付状态更新出错，请稍后重试");
      }
    })
    .catch(() => {});
};

// 取消按钮操作
const handleCancel = (row) => {
  ElMessageBox.confirm(`确认取消订单 ${row.id} 吗？`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        const response = await orderApi.cancelOrder(row.id);
        if (response.code === 200) {
          ElMessage.success("订单取消成功");
          // 刷新订单列表
          getList();
        } else {
          ElMessage.error(response.message || "订单取消失败");
        }
      } catch (error) {
        console.error("取消订单出错", error);
        ElMessage.error("取消订单出错，请稍后重试");
      }
    })
    .catch(() => {});
};

// 获取订单状态类型
const getOrderStatusType = (status) => {
  if (status === "normal") return "primary";
  if (status === "cancelled") return "info";
  if (status === "used") return "success";
  return "info";
};

// 获取订单状态文本
const getOrderStatusText = (status) => {
  if (status === "normal") return "正常";
  if (status === "cancelled") return "已取消";
  if (status === "used") return "已使用";
  return "未知状态";
};
</script>

<style lang="scss" scoped>
.order-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;

  .filter-container {
    padding: 15px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    background-color: #f5f7fa;
    border-radius: 4px;
    flex-wrap: wrap;

    .el-button {
      margin-left: 10px;
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
